// 左侧菜单
angular.module('HTRD_AutoConsole.A').directive('userSelect',[function() {
  var link = function(s, e) {
      var $scope, $node;

      var activeMenu = function(item) {
        $scope.defaultText = item.title;
        $scope.callBack && $scope.callBack(item);
      };

      var selectbox = function(item){
        var len = $scope.list.length;  //获取长度;
        var count = 0;
        $scope.defaultText = [];
        var ids = [];
        $scope.texts = [];
        item.checked = !!!item.checked;
        $scope.list.map(function(item){
          if(item.checked){
            $scope.texts.push(item.title);
            ids.push(item.id);
            count++;
          }
        });
        count == 0? $scope.defaultText = "请选择用户" : $scope.defaultText = $scope.texts.join(',');
        $scope.$emit('userList',{
          userIds: ids
        })
        console.log(ids);
        $scope.checkedAll = len === count;
      };


      var selectAll = function (item) {
        var ids = [];
        $scope.texts = [];
        var count = 0;
        $scope.checkedAll = !!!$scope.checkedAll;
          $scope.list.map(function(item){
            item.checked = $scope.checkedAll;
            if(item.checked){
              $scope.texts.push(item.title);
              ids.push(item.id);
              count++;
              //console.log(ids)
            }
          });
        console.log(ids);
        $scope.$emit('userList',{
          userIds: ids
        });
        count == 0? $scope.defaultText = "请选择用户" : $scope.defaultText = $scope.texts.join(',');
      };

      var parseDOM = function() {
        $scope = s;
        $node = $(e[0]);
      };

      var bindListener = function() {
        $scope.activeMenu = activeMenu;
        $scope.selectbox = selectbox;
        $scope.selectAll = selectAll;
      };

      var initPlugins = function() {
        $scope.texts = [];
        $scope.checkedAll = false;
        $node.find(".dropdown-menu").on('click', function (e) {
           e.stopPropagation();
         });

      };

      parseDOM();
      bindListener();
      initPlugins();
  };

  return {
      'replace': true,
      'restrict' : 'AEC',
      'scope': {
        'list': '=',
        'defaultText': '=',
        'callBack': '='
      },
      'link': link,
      'templateUrl': 'view/directive/util/userSelect.html'
  };
}]);
